import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/common/class/date/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/video.dart';
import 'package:qgchat/http/models/invitationInfoModel.dart';
import 'package:qgchat/http/models/taglistModel.dart';
import 'package:qgchat/http/models/tokenuserInfoModel.dart';
import 'package:qgchat/states/states_model/user.dart';

import 'Bloc/InvitationInfoBloc.dart';
import 'Bloc/TargetInfoBloc.dart';

class EndCall extends StatefulWidget {
  final int inv;
  final String targetToken;
  EndCall({
    @required this.inv,
    @required this.targetToken,
    Key key,
  }) : super(key: key);

  @override
  _EndCallState createState() => _EndCallState();
}

class _EndCallState extends State<EndCall> {
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<TargetInfoBlocBloc>(
          create: (BuildContext context) => TargetInfoBlocBloc(
            targetToken: widget.targetToken,
          ),
        ),
        BlocProvider<InvitationInfoBlocBloc>(
          create: (BuildContext context) => InvitationInfoBlocBloc(
            inv: widget.inv,
          ),
        ),
      ],
      child: _BlocInit(
        child: Scaffold(
          backgroundColor: Colors.grey,
          body: Stack(
            alignment: Alignment.center,
            children: [
              _Background(),
              _FilterBlur(),
              _UserInfo(),
              _Time(),
              _Profit(),
              _BackBtn(),
            ],
          ),
        ),
      ),
    );
  }
}

// 背景
class _Background extends StatelessWidget {
  const _Background({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TargetInfoBlocBloc, TokenuserInfoModel>(
      builder: (context, state) {
        if (state.id == null) return Container();

        return Container(
          width: w100(context),
          height: h100(context),
          child: CachedNetworkImage(
            imageUrl: '${state.memberHead}',
            width: px(102),
            height: px(102),
            fit: BoxFit.cover,
            errorWidget: (context, url, error) {
              return Config.errorNetImage;
            },
          ),
        );
      },
    );
  }
}

// 毛玻璃层
class _FilterBlur extends StatelessWidget {
  const _FilterBlur({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 30, sigmaY: 30),
      child: Container(
        color: Colors.white.withAlpha(0),
      ),
    );
  }
}

// 用户信息
class _UserInfo extends StatelessWidget {
  const _UserInfo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final top = MediaQuery.of(context).padding.top;
    return BlocBuilder<TargetInfoBlocBloc, TokenuserInfoModel>(
      builder: (context, state) {
        if (state.id == null) return Container();

        return Positioned(
          top: top + px(128),
          child: Column(
            children: [
              Container(
                width: px(180),
                height: px(180),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(90),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black12,
                      offset: Offset(0.0, 1),
                      blurRadius: 1,
                      spreadRadius: 1,
                    ),
                  ],
                  image: DecorationImage(
                    fit: BoxFit.cover,
                    image: NetworkImage(
                      state.memberHead,
                    ),
                  ),
                ),
              ),
              SizedBox(height: px(40)),
              Text(
                state.memberNickname,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: px(38),
                  shadows: [
                    Shadow(
                      color: Colors.black26,
                      blurRadius: 1,
                      offset: Offset(1, 1),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

// 通话计时
class _Time extends StatelessWidget {
  const _Time({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final top = MediaQuery.of(context).padding.top;
    return Positioned(
      top: top + px(450),
      child: Column(
        children: [
          Text(
            '通话结束',
            style: TextStyle(
              color: Colors.white,
              fontSize: px(34),
              fontWeight: FontWeight.bold,
              shadows: [
                Shadow(
                  color: Colors.black26,
                  blurRadius: 1,
                  offset: Offset(1, 1),
                ),
              ],
            ),
          ),
          SizedBox(height: px(24)),
          BlocBuilder<InvitationInfoBlocBloc, InvitationInfoModel>(
            builder: (context, state) {
              String str = '计算中...';
              if (state.id != null) {
                int endtime = int.parse(state.endtime);
                int talktime = int.parse(state.talktime);
                str = Date.difference(talktime, endtime) ?? "00:00:00";
              }
              return Text(
                '通话时长：$str',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: px(28),
                  shadows: [
                    Shadow(
                      color: Colors.black26,
                      blurRadius: 1,
                      offset: Offset(1, 1),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}

// 直播收益
class _Profit extends StatelessWidget {
  const _Profit({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final top = MediaQuery.of(context).padding.top;
    return Positioned(
      top: top + px(700),
      child: Container(
        width: w100(context),
        padding: EdgeInsets.symmetric(horizontal: px(50)),
        child: Column(
          children: [
            Provide<UserState>(
              builder: (context, child, state) {
                final isAnchor = state.info.memberType == 1;
                return Text(
                  '${isAnchor ? '直播收益' : '本次消费'}(金币)',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: px(26),
                    shadows: [
                      Shadow(
                        color: Colors.black26,
                        blurRadius: 1,
                        offset: Offset(1, 1),
                      ),
                    ],
                  ),
                );
              },
            ),
            SizedBox(height: px(55)),
            BlocBuilder<InvitationInfoBlocBloc, InvitationInfoModel>(
              builder: (context, state) {
                bool ready = state.id != null;
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _ProfitItem(
                      count: ready ? state.giftGlod : 0,
                      title: '礼物',
                    ),
                    _ProfitItem(
                      count: ready ? state.gold : 0,
                      title: '视频通话',
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

// 直播收益单元
class _ProfitItem extends StatelessWidget {
  final int count;
  final String title;
  const _ProfitItem({
    @required this.count,
    @required this.title,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          "$count",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
            fontSize: px(68),
            shadows: [
              Shadow(
                color: Colors.black26,
                blurRadius: 1,
                offset: Offset(1, 1),
              ),
            ],
          ),
        ),
        SizedBox(height: px(24)),
        Text(
          "$title",
          style: TextStyle(
            color: Colors.white,
            fontSize: px(26),
            shadows: [
              Shadow(
                color: Colors.black26,
                blurRadius: 1,
                offset: Offset(1, 1),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

// 返回首页按钮
class _BackBtn extends StatelessWidget {
  const _BackBtn({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: px(60),
      child: Container(
        width: px(702),
        height: px(100),
        child: FlatButton(
          onPressed: () {
            Navigator.of(context).popUntil(
              (route) => route.settings.name == '/',
            );
          },
          color: col('4bd5e2'),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(px(50)),
          ),
          child: Text(
            "返回首页",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(32),
            ),
          ),
        ),
      ),
    );
  }
}

class _BlocInit extends StatefulWidget {
  final Widget child;
  _BlocInit({this.child, Key key}) : super(key: key);

  @override
  __BlocInitState createState() => __BlocInitState();
}

class __BlocInitState extends State<_BlocInit> {
  @override
  void initState() {
    super.initState();
    context.bloc<TargetInfoBlocBloc>().listen((state) {
      if (state.id == null) return;
      final type = Provide.value<UserState>(context).info.memberType;
      if (type == 1) return;
      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(px(22)),
            topRight: Radius.circular(px(22)),
          ),
        ),
        builder: (context) {
          return _Evaluate(anchorId: state.id);
        },
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

class _Evaluate extends StatefulWidget {
  final int anchorId;
  _Evaluate({this.anchorId, Key key}) : super(key: key);

  @override
  __EvaluateState createState() => __EvaluateState();
}

class __EvaluateState extends State<_Evaluate> {
  // 标签列表
  final List<TaglistModel> tags = [];

  // 选中标签id列表
  final List<int> selectIds = [];

  // 选中标签列表
  List<TaglistModel> get selects {
    final ids = selectIds.toSet().toList();
    final arr = tags.where((tag) => ids.contains(tag.id)).toList();
    return arr;
  }

  @override
  void initState() {
    super.initState();
    // 标签列表
    VideoApis.taglist().then((arr) {
      tags.addAll(arr);
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: px(800),
      child: Column(
        children: <Widget>[
          Container(
            height: px(88),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: col("edeff2"),
                  width: 1,
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                FlatButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text(
                    "取消",
                    style: TextStyle(
                      color: col("606266"),
                      fontSize: px(34),
                    ),
                  ),
                ),
                Text(
                  "评价主播",
                  style: TextStyle(
                    color: col("303133"),
                    fontSize: px(34),
                  ),
                ),
                FlatButton(
                  onPressed: () {
                    if (selectIds.length == 0) return;
                    if (selectIds.length > 3) return;
                    VideoApis.commentZhubo(
                      widget.anchorId,
                      selectIds,
                    ).then((value) {
                      toast('评价成功');
                      Navigator.pop(context);
                    });
                  },
                  child: Text(
                    "确定",
                    style: TextStyle(
                      color: col("5640c6"),
                      fontSize: px(34),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: px(712),
            child: ListView(
              children: <Widget>[
                Container(
                  width: w100(context),
                  padding: EdgeInsets.symmetric(
                    horizontal: px(55),
                    vertical: px(30),
                  ),
                  child: Wrap(
                    spacing: px(15),
                    runSpacing: px(20),
                    children: tags.map<Widget>((item) {
                      return GestureDetector(
                        onTap: () {
                          if (!selectIds.contains(item.id) &&
                              selectIds.length < 3) {
                            selectIds.add(item.id);
                          }
                          setState(() {});
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: px(22),
                            vertical: px(12),
                          ),
                          decoration: BoxDecoration(
                            color: col(
                              "${item.xingxiangcolor.replaceAll('#', '')}",
                            ),
                            borderRadius: BorderRadius.circular(
                              px(27),
                            ),
                          ),
                          child: Text(
                            "${item.usertagName}",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: px(26),
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                ),
                Container(
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.symmetric(
                    horizontal: px(55),
                    vertical: px(30),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "当前选择的标签",
                        style: TextStyle(
                          color: col("909399"),
                          fontSize: px(22),
                        ),
                      ),
                      Text(
                        "最多选择3个印象标签",
                        style: TextStyle(
                          color: col("909399"),
                          fontSize: px(22),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: w100(context),
                  padding: EdgeInsets.symmetric(
                    horizontal: px(55),
                    vertical: px(30),
                  ),
                  child: Wrap(
                    spacing: px(15),
                    runSpacing: px(20),
                    children: selects.map<Widget>((item) {
                      return GestureDetector(
                        onTap: () {
                          selectIds.removeWhere((id) => id == item.id);
                          setState(() {});
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: px(22),
                            vertical: px(12),
                          ),
                          decoration: BoxDecoration(
                            color: col(
                              "${item.xingxiangcolor.replaceAll('#', '')}",
                            ),
                            borderRadius: BorderRadius.circular(
                              px(27),
                            ),
                          ),
                          child: Text(
                            "${item.usertagName}",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: px(26),
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
